package handlers

import (
	"main_service/services"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type APIHandler struct {
	klineService services.KlineService
	cacheService *services.CacheService
}

func NewAPIHandler() *APIHandler {
	return &APIHandler{
		klineService: services.KlineService{},
		cacheService: services.NewCacheService(),
	}
}

func (h *APIHandler) GetKlines(c *gin.Context) {
	exchange := c.Query("exchange")
	symbol := c.Query("symbol")
	interval := c.Query("interval")
	startTimeStr := c.Query("start_time")
	endTimeStr := c.Query("end_time")

	if exchange == "" || symbol == "" || interval == "" || startTimeStr == "" || endTimeStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Missing required parameters"})
		return
	}

	// 解析时间 (格式: YYYYMMDD)
	startTime, err := time.Parse("20060102", startTimeStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid start_time format, expected YYYYMMDD"})
		return
	}

	endTime, err := time.Parse("20060102", endTimeStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid end_time format, expected YYYYMMDD"})
		return
	}

	// 设置结束时间为当天的最后一秒
	endTime = endTime.Add(24*time.Hour - time.Second)

	klines, err := h.klineService.GetKlines(exchange, symbol, interval, startTime, endTime)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, klines)
}

func (h *APIHandler) GetStockList(c *gin.Context) {
	// 从缓存获取全量数据
	stocks := h.cacheService.GetStockList()
	c.JSON(http.StatusOK, stocks)
}
